<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\UserAuth;
use App\Models\UserMenus;
use App\Models\UserAuthMenus;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\Facades\JWTAuth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Hash;

// 角色
class UserAuthController extends Controller
{
    // 列表
    public function index(Request $request)
    {
        $keywords = $request->input('keywords', ''); // 查询关键字
        $is_all = $request->input('is_all', 0); //不分页获取全部数据

        if($is_all){
            $data = UserAuth::query()
            ->where($this->getAppWhere())
            ->when($keywords, function ($query) use ($keywords) {
                $query->where('name', 'like', "%{$keywords}%");
            })
             ->orderBy('id')
            ->get()
            ->toArray();
        }else{
            $data = UserAuth::query()
            ->where($this->getAppWhere())
            ->when($keywords, function ($query) use ($keywords) {
                $query->where('name', 'like', "%{$keywords}%");
            })
            ->orderByDesc('id')
            ->paginate(env('PAGE_SIZE', 10));
        }
       
        return showData($data);    
    }

    // 新增
    public function store(Request $request)
    {
        $validate = Validator::make($request->all(), [
            'name' => 'required|max:20',
            'project_id' => 'required|max:20',
            'street_id' => 'required|max:20',
            'village_id' => 'required|max:20',
        ], [
            'name.required' => '请输入名称',
            'project_id.required' => '请输入项目名称',
            'street_id.required' => '请输入街道',
            'village_id.required' => '请输入村庄',
        ]);

        if ($validate->fails()) {
            return showError($validate->errors()->first());
        }

        $data = $validate->getData();

        $Info['name']=$data['name'];
        $Info['project_id']=$data['project_id'];
        $Info['street_id']=$data['street_id'];
        $Info['village_id']=$data['village_id'];
        try {
            $add=UserAuth::query()->create($Info);
            return showSuccess('添加成功！');
        } catch (\Exception $e) {
            return showError($e->getMessage());
        }
    }

    // 编辑
    public function update($Id, Request $request)
    {
        if (empty($Id)) {
            return showError('id不能为空!');
        }
        // 验证
        $validate = Validator::make($request->all(), [
            'name' => 'required|max:20',
            'project_id' => 'required|max:20',
            'street_id' => 'required|max:20',
            'village_id' => 'required|max:20',
        ], [
            'name.required' => '请输入名称',
            'project_id.required' => '请输入项目名称',
            'street_id.required' => '请输入街道',
            'village_id.required' => '请输入村庄',
        ]);

        if ($validate->fails()) {
            return showError($validate->errors()->first());
        }

        $data = $validate->getData();

        $Info['name']=$data['name'];
        $Info['project_id']=$data['project_id'];
        $Info['street_id']=$data['street_id'];
        $Info['village_id']=$data['village_id'];

        try {
            $update = UserAuth::query()->where('id', $Id)->update($Info);
            return showSuccess('编辑成功！');
        } catch (\Exception $e) {
            return showError($e->getMessage());
        }
    }

    // 删除
    public function destroy($id)
    {
        if (empty($id)) {
            return showError('参数错误！');
        }

        $admin = UserAuth::query()->where('id', $id)->first();
        if (empty($admin)) {
            return showError('删除项不存在');
        }
        try {
            $delete = UserAuth::query()->where('id', $id)->delete();
            return showSuccess('删除成功！');
        } catch (\Exception $e) {
            return showError($e->getMessage());
        }
    }

    // 详情
    public function show($id)
    {
        if (empty($id)) {
            return showError('参数错误');
        }
   
        $data = UserAuth::query()
            ->where('id', $id)
            ->first();

        if (empty($data)) {
            return showError('获取信息失败');
        }

        return showData($data);
    }


    // 菜单列表
    public function userMenusList(Request $request)
    {
        $validate = Validator::make($request->all(), [
            'auth_id' => 'required|max:20',
        ], [
            'auth_id.required' => '请输入角色id',
        ]);

        if ($validate->fails()) {
            return showError($validate->errors()->first());
        }

        $params = $validate->getData();

        $menus_ids = UserAuthMenus::query()->where('auth_id',$params['auth_id'])->value('menus_ids');

        $user_menus = UserMenus::query()
                ->select('id','name','slug','url','pid')
                ->get()
                ->toArray();

        foreach($user_menus as &$v){
            if(in_array($v['id'],explode(',',$menus_ids))){
                $v['select']=1;
            }else{
                $v['select']=0;
            }
        }        
        
        $data=$this->getTree($user_menus);
      
        return showData($data);    
    }


    function getTree($array,$parent_id=0){
        $new=[];
        foreach($array as $k=>$v){
            if($v['pid']==$parent_id){
                $v['child']= self::getTree($array,$v['id']);
                if (!$v['child']) {
                    unset($v['child']);
                }
                $new[] = $v;
            }
        }
        return $new;
    }


     // 新增菜单权限
     public function addUserMenus(Request $request)
     {
        $validate = Validator::make($request->all(), [
            'auth_id' => 'required|max:20',
            'menus_ids' => 'required',
        ], [
            'auth_id.required' => '请输入角色id',
            'menus_ids.required' => '请输入菜单权限ids',
        ]);

        if ($validate->fails()) {
            return showError($validate->errors()->first());
        }

        $params = $validate->getData();

        try {
            $UserAuthMenus = UserAuthMenus::query()->updateOrCreate(
                [
                    'auth_id' => $params['auth_id'],
                ],$params);

            return showSuccess('编辑成功！');
        } catch (\Exception $e) {
            return showError($e->getMessage());
        }
     }
}

